<?php

namespace App\Admin\Controllers\goods;

use App\Admin\Controllers\goods\actions\OrderPass;
use App\Common\statement\CommonStatement;
use App\Models\fund\Coupon;
use App\Models\goods\Order;
use App\Models\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class OrderController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '订单';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order);

//        $grid->tools(function (Grid\Tools $tools) {
//            $tools->append(new OrderPass());
//        });

        $grid->model()->orderByDesc('id');
        $grid->disableExport();
        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->column(1/3, function ($filter) {

                $filter->where(function ($query) {

                    $query->whereHas('user',function ($query){
                        $query->where('uuid', 'like', "%{$this->input}%");
                    })
                        ->orWhere('id', 'like', "%{$this->input}%");

                },__('Uuid'));

                $filter->where(function ($query) {
                    $query->where('out_trade_no', 'like', "%{$this->input}%")
                        ->orWhere('trade_no', 'like', "%{$this->input}%");

                },__('订单号'));


            });

            $filter->column(1/3, function ($filter) {

                $filter->where(function ($query) {
                    $query->whereHas('user',function ($query){
                        $query->where('phone', 'like', "%{$this->input}%")
                            ->orWhere('name', 'like', "%{$this->input}%");
                    });

                },'昵称手机');
                $filter->equal('status',__('Status'))->select(CommonStatement::order_status);

            });

            $filter->column(1/3, function ($filter) {
                $filter->between('created_at',__('Created at'))->datetime();
            });

        });

        $grid->header(function ($query) {
            // 查询出已支付状态的订单总金额
            $data = $query->where('status','!=',0)->sum('total_price');
            $rebate_money = $query->where('status','!=',0)->sum('rebate_money');

            $profit = $data - $rebate_money;

            $str  = '<div>';
            $str .= "  <span style='padding: 10px;'>业绩 ： $data  </span>";
            $str .= "  <span style='padding: 10px;'>返点 ： $rebate_money  </span>";
            $str .= "  <span style='padding: 10px;'>毛利 ： $profit  </span>";
            $str .= '</div>';
            return $str;

        });

        $grid->column('id', __('Id'));
        $grid->column('user_id', __('User id'));
        $grid->column('user.header_img', __('header_img'))
            ->lightbox(['width' => 50, 'height' => 50, 'class' => ['circle', 'thumbnail']]);

        $grid->column('user.name', __('Name'));
        $grid->column('order_no', __('Order No'))->display(function ($s){
            if ($s == 'buy_member'){
                return "会员[{$this->remark}]购买";
            }
            return $s;
        });
//        $grid->column('goods_id', __('Goods id'));
//        $grid->column('goods.img', __('Img'))->lightbox(['width' => 50, 'height' => 50, 'class' => ['circle', 'thumbnail']]);;
//        $grid->column('goods.name', __('商品名称'));
//        $grid->column('type_name', __('Type name'));
//        $grid->column('spec', __('Spec'));
//        $grid->column('num', __('Num'));
//        $grid->column('price', __('单价'));
        $grid->column('total_price', __('Total price'));
        $grid->column('rebate_money', __('Rebate money'));
        $grid->column('status', __('Status'))->display(function ($status){
            return CommonStatement::order_status[$status];
        });
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));
//        $grid->column('detail', __('Detail'));
//        $grid->column('phone', __('Phone'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('user_id', __('User id'));
        $show->field('goods_id', __('Goods id'));
        $show->field('type_name', __('Type name'));
        $show->field('spec', __('Spec'));
        $show->field('num', __('Num'));
        $show->field('price', __('Price'));
        $show->field('total_price', __('Total price'));
        $show->field('money', __('Money'));
        $show->field('status', __('Status'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('detail', __('Detail'));
        $show->field('phone', __('Phone'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Order);
        //TODO 测试运费修改
        $form->column(1/2, function ($form) {
            $form->number('user_id', __('User id'))->readonly();
            $form->text('order_no', __('Order No'))->readonly();
            $form->decimal('money', __('余额支付金额'))->default(0.00)->readonly();
            $form->decimal('pay_money', __('第三方支付扣款额'))->default(0.00)->readonly();
            $form->decimal('pay_info', __('支付详情'))->default(0.00)->readonly();
            $form->decimal('total_price', __('Total price'));
            $form->decimal('postage', __('Postage'))->readonly();
            $form->switch('is_safe', __('退货免邮'))
                ->states(CommonStatement::default_switch)
                ->default(CommonStatement::default_no_status);

            $form->switch('is_sign_for', __('是否扫码签收'))
                ->states(CommonStatement::default_switch)
                ->default(CommonStatement::default_no_status);

            $form->text('user_name', __('联系人'));
            $form->mobile('phone', __('Phone'));
            $form->text('detail', __('联系地址'));
            $form->select('nu_code', __('快递公司'))->options(getExpresses());
            $form->text('nu', __('快递编号'));
            $form->select('status', __('Status'))->options(CommonStatement::order_status);
        });


        $form->column(1/2, function ($form) {

            $form->hasMany('details', "下单商品",function (Form\NestedForm $form) {

                $form->display('goods_id', __('Goods id'))->readonly();
                $form->display('goods_name',__('商品名称'))->readonly();

//                $form->image('goods_img',__('Img'))->readonly();
                $form->decimal('price', __('单价'))->readonly();
                $form->display('num', __('Num'))->readonly();
                $form->decimal('total_price', __('Total price'));
                $form->decimal('postage', __('Postage'))->readonly();

                $form->display('type_name', __('Type name'));
                $form->display('spec', __('Spec'));
                $form->display('remark', __('Remark'));
            })->disableCreate()->disableDelete();
        });






        return $form;
    }

    // 审核操作
    public function orderPass(Request $request)
    {
        $status = $request->post('status');
        $bag = $request->post('bag')['ids'] ?? [];


        $update = [];


        /** @var Collection $activities */
        $activities = Order::where('status',4)->find($bag);
        $activities->each(function ($activity) use ($status,$update) {

            if ($status == 5){//退款通过
                if ($activity->money > 0 || $activity->pay_money > 0){//使用了余额或者第三方支付  退回余额
                    $user = User::find($activity->user_id);
                    $money = 0;
                    if ($activity->money > 0){
                        $money = $activity->money;
                    }

                    if ($activity->pay_money > 0){

                        $money += $activity->pay_money;
                    }

                    if ($user){
                        $user->increment('money',$money);
                    }
                }

                if ($activity->coupon_id){//使用了优惠券
                    $coupon = Coupon::find($this->coupon_id);
                    if ($coupon){
                        $coupon->status = 1;
                        $coupon->save();
                    }
                }
            }

            $activity->update(['status' => $status]);

        });

        return response()->json([
            'status' => true,
            'message' => '操作成功'
        ]);
    }



}
